//
//  DHUserAccount.swift
//  Weibo
//
//  Created by Holfioo on 15/9/4.
//  Copyright © 2015年 Holfioo. All rights reserved.
//

import UIKit

class DHUserAccount: NSObject, NSCoding {
    // 字典属性
    var access_token: String?
    
    var uid: String?
    // 查看是否过期
    var expiresDate: NSDate?
    // 常量，秒为单位
    var expires_in: NSTimeInterval = 0 {
        didSet {
            // 计算从当前的日期计算的天数。
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    // 其他属性，能拿的都拿
    var name: String?
    var avatar_large: String? // 大图像
    
    init(dict: [String: AnyObject]) {
        super.init()
        
        //字典转模型
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        // 空值
    }
    static let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    // 保存用户信息
    func saveUserAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: DHUserAccount.path)
    }
    // 加载存档信息
    class func loadUserAccount() -> DHUserAccount? {
        // 返回值可能为空。~
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(DHUserAccount.path) as? DHUserAccount
        /// 计算日期大，代表还没过期。相等代表当天过期
        if let date = account?.expiresDate {
            if date.compare(NSDate()) == NSComparisonResult.OrderedDescending { // 代表第一个数比第二个数大。(未过期)
            return account
            }
        }
        return nil
    }
    
    // 重写print方法
    override var description: String {
        let key = ["access_token", "expires_in", "uid", "expiresDate", "name", "avatar_large"]
        // 用模型反求字典
        return dictionaryWithValuesForKeys(key).description
    }
    
    //MARK: - 归档解档属性
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
        // 解档
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
}
